package com.mrzhou.study.struct.stack;

/**
 * 栈结构:
 *  介绍: 栈是一种线性结构, 所以可以使用数组或这个链表实现
 *  基本定义: 先进的后出, 后进的先出, 参考弹夹中的子弹
 *  栈的基本操作: 出栈(pop)、压栈(push)
 *
 */
public class ArrayStack<T> {

    private int maxSize;
    private Object[] stack ;
    private int top = -1;

    public ArrayStack(int size) {
        this.maxSize = size;
        this.stack = new Object[size];
    }

    /**
     * 压栈或者说入栈
     * @param elem
     */
    public void push(T elem) {
        if(isFull()) {
            System.out.printf("超过栈最大的索引长度, 最大索引: %d\t入参索引: %d",  maxSize);
            return;
        }
        top++;
        stack[top] = elem;
    }

    /**
     * 出栈
     * @return
     */
    public T pop() {
        if(isEmpty()) {
            System.out.printf("当前栈已空\n");
            return null;
        }
        Object elem = stack[top];
        top--;
        return (T) elem;
    }

    public T peek() {
        if (isEmpty()) {
            return null;
        }
        return (T) stack[top];
    }

    public static void main(String[] args) {
        ArrayStack<Integer> stack = new ArrayStack<>(200);
        for(int i = 0; i < 100; i++) {
            stack.push(i);
        }
        for(int i = 1; i <= 100; i++) {
            if(i % 10 == 0) {
                System.out.print(stack.pop() + "\n");
            } else  {
                System.out.print(stack.pop() + ", ");
            }
        }
    }

    public boolean isFull() {
        return top == maxSize-1;
    }

    public boolean isEmpty() {
        return this.top == -1;
    }

    public int stackPrint(int i) {
        if(i > 3) {
            return i;
        }
        System.out.print(i + " ");
        i++;
        return stackPrint(i);
    }

    /*
    public static void main(String[] args) {
        ArrayStack stack = new ArrayStack(10);
        stack.stackPrint(0);
    }
*/

}
